<?php
declare(strict_types=1);

namespace Service\PushService;

use Service\BaseService;
use Service\VenderClient\YunCangApi\YunCangApiClient;
use Service\ChannelService\ChannelWxService;
use App\Model\BbcModel\PushAgain;
use App\Model\BbcModel\Order;
use App\Model\BbcModel\OrderGoods;
use Service\Code\Normal;

/**
 * 推送云仓数据服务
 * @author chenshubo
 */
class PushYunCangApiService extends BaseService
{
    /**
     * 推送云仓API接口服务
     * @param int $cid
     * @param string $method
     * @param array $body
     */
    public function push(int $cid,string $method,array $body = [])
    {
        $channel_config = ChannelWxService::instance()->queryWxConfig($cid);
        return (new YunCangApiClient($channel_config))->callApi($method,$body);
    }
    
    
    /**
     * 推送云仓订单数据(未使用)
     * @param int $cid
     * @param int $mn_sid
     * @param array $extra
     */
    public function pushYunCangOrder(int $cid,int $mn_sid,array $extra)
    {
        $scan_rece_type = $extra['scan_rece_type'];
        $order_sn       = $extra['order_sn'];
        $time           = $extra['time'];
        $order_id       = $extra['order_id'];
        $mid            = $extra['mid'];
    
        //向云仓推送订单
        $companyconfig  = StoreConfigService::instance()->getConfig('e_company',$mn_sid);
    
        //获取支付方式
        $payway         = CashPayService::instance()->pay_way[$scan_rece_type];
        $orderPayData   = [
            'cid'               =>  $cid,
            'payTime'           =>  $time,
            'enterpriseNum'     =>  $companyconfig['eCompanyCode']??'',
            'enterpriseName'    =>  $companyconfig['eCompanyName']??'',
        ];
    
        if( $payway == 'hnapay' )
        {
            $hnapayconfig                   = StoreConfigService::instance()->getConfig('hnapay_pay',$mn_sid);
            $hnapayconfigdata               = $hnapayconfig;
            $orderPayData['payWay']         = 4;
            $orderPayData['payCommanyName'] = $hnapayconfigdata['payCommanyName']??'';
            $orderPayData['payCommanyCode'] = $hnapayconfigdata['payCommanyCode']??'';
        }
        elseif( $payway == 'alipay' )
        {
            $orderPayData['payWay']             = 6;
            $orderPayData['payCommanyName']     = '支付宝(中国)网络技术有限公司';
            $orderPayData['payCommanyCode']     = '31222699S7';
        }
        else
        {
            $orderPayData['payWay']             = 5;
            $orderPayData['payCommanyName']     = '财付通支付科技有限公司';
            $orderPayData['payCommanyCode']     = '4403169D3W';
        }
    
        //运单申报结果
        $logisticReport = $extra['logisticReport'];
    
        $orderPayData["payDecarleResponse"]     = $pay['data']['initalResponse'] ?? '';
        $orderPayData["payDecarleRequest"]      = $pay['data']['initalRequest'] ?? '';
        $orderPayData["orderSn"]                = $order_sn;
        $orderPayData["paySerial"]              = $pay['data']['transaction_id'] ?? '';
        $orderPayData["logisticNo"]             = $logisticReport['data']['waybillNo'] ??'';
        $orderPayData["logisticCode"]           = $logisticreport['data']['logisticCustomCode']??"";
        $orderPayData["logisticName"]           = $logisticreport['data']['logisticCustomName']??'';
        $orderPayData["logisticWayBillContent"] = $logisticreport['data']['originData']??'';
    
        //订单创建数据
        $orderCreateData = $extra['orderCreate'];
    
        //预警配置
        $monitor_config = ChannelConfigService::instance()->getChannelConfig('monitor_mobile',$cid);
        $mobile = $monitor_config['mobile']??'';
    
        //运单申报失败，发送监控短信
        if( $logisticReport['code'] != Normal::SUC )
        {
            $message = [
                'cid'       => $cid,
                'mid'       => $mid,
                'mobile'    => $mobile,
                'code'      => "运单申报失败,订单号[{$order_sn}],失败原因[{$logisticReport['msg']}]",
                'temp'      => 'failorder'
                    ];
            SmsService::instance()->publishSmsToMg($message);
            //写入重新推送队列
            $push = [];
            $push['sync_data']  = json_encode($orderCreateData, JSON_UNESCAPED_UNICODE);
            $push['code']       = 0;
            $push['msg']        = '运单申报失败';
            $push['pay_data']   = json_encode($orderPayData, JSON_UNESCAPED_UNICODE);
            $push['order_id']   = $order_id;
            PushAgain::instance()->add($push);
        }
        else
        {
            $push_order_create_result = PushYunCangApiService::instance()->push($cid,'createOrder',$orderCreateData);
            if( $push_order_create_result['code'] != Normal::SUC )
            {
                $push = [];
                $push['sync_data']  = json_encode($orderCreateData, JSON_UNESCAPED_UNICODE);
                $push['code']       = $push_order_create_result['code'];
                $push['msg']        = $push_order_create_result['msg'];
                $push['pay_data']   = json_encode($orderPayData, JSON_UNESCAPED_UNICODE);
                $msg = $push_order_create_result['msg'] ?? '请求失败';
                $message = [
                    'cid'       => $cid,
                    'mid'       => $mid,
                    'mobile'    => $mobile,
                    'code'      => "推送云仓订单创建失败,订单号[{$order_sn}],失败原因[{$msg}]",
                    'temp'      => 'failorder'
                        ];
                SmsService::instance()->publishSmsToMg($message);
                $push['order_id'] = $order_id;
                PushAgain::instance()->add($push);
            }
            else
            {
                $returnData = $push_order_create_result['data']['orderItems'];
                $return_sn = [];
                foreach ($returnData as $v) {
                    $skuCodes = array_column($v['goods_items'], 'goodsSku');
                    foreach ($skuCodes as $value) {
                        $return_sn[$value] = $v['orderNo'];
                    }
                }
    
                Order::instance()->edit(['id'=>$order_id], ['push_success'=>1]);
                $editgoods= OrderGoods::instance()->lists(['order_id'=>$order_id]);
                foreach ($editgoods as $k => $v)
                {
                    $stb_sn = $return_sn[$order_goods_data[$v['goods_id']]];
                    OrderGoods::instance()->edit(['id'=>$v['id']], ['stb_sn'=>$stb_sn]);
                }
                $pushPayResult = PushYunCangApiService::instance()->sendToStoB($cid,'OrderPay',$orderPayData);
                if( $pushPayResult['code'] == Normal::SUC )
                {
                    Order::instance()->edit(['id'=>$order_id], ['pay_success'=>1]);
                }
                else
                {
                    $payAgain= PushAgain::instance()->info(['order_id'=>$order_id]);
                    if($payAgain)
                    {
                        PushAgain::instance()->edit(['id'=>$payAgain['id']],['pay_data'=>json_encode($orderPayData, JSON_UNESCAPED_UNICODE)]);
                    }
                    else
                    {
                        PushAgain::instance()->add([
                            'pay_data'  => json_encode($orderPayData, JSON_UNESCAPED_UNICODE),
                            'order_id'  => $order_id,
                            'cd'        => time(),
                            'msg'       => $pushPayResult['msg']
                        ]);
                    }
                }
            }
        }
    }
    
    public function pushYunCangOrderByPushAgain(int $cid,array $pushagain) {
        if(empty($pushagain['sync_data'])){
            return Normal::returnCode(Normal::FAIL,'参数缺失');
        }
        $orderCreateData= json_decode($pushagain['sync_data'],true);
        $push_order_create_result = $this->push($cid,'createOrder',$orderCreateData);
        $againEditdata=[
            'code'=>$push_order_create_result['code'],
            'msg'=>$push_order_create_result['msg'],
            'md'=>time()
        ];
        if($push_order_create_result['code']==Normal::SUC){
            $returnData = $push_order_create_result['data']['orderItems'];
            $return_sn = [];
            foreach ($returnData as $v) {
                $skuCodes = array_column($v['goods_items'], 'goodsSku');
                foreach ($skuCodes as $value) {
                    $return_sn[$value] = $v['orderNo'];
                }
            }

            Order::instance()->edit(['id'=>$pushagain['order_id']], ['push_success'=>1]);
            $editgoods= OrderGoods::instance()->lists(['order_id'=>$pushagain['order_id']]);
            foreach ($editgoods as $k => $v) 
            {
                $stb_sn = $return_sn[$v['skucode']];
                OrderGoods::instance()->edit(['id'=>$v['id']], ['stb_sn'=>$stb_sn]);
            }
            $againEditdata['status']=1;
        }
        PushAgain::instance()->edit(['id'=>$pushagain['id']], $againEditdata);
        return $push_order_create_result;
    }
    public function pushYunCangPayByPushAgain(int $cid,array $pushagain) {
        if(empty($pushagain['pay_data'])){
            return Normal::returnCode(Normal::FAIL,'参数缺失');
        }
        $orderPayData= json_decode($pushagain['pay_data'],true);
        $pushPayResult = $this->push($cid,'OrderPay',$orderPayData);
        $againEditdata=[
            'code'=>$pushPayResult['code'],
            'msg'=>$pushPayResult['msg'],
            'md'=>time()
        ];
        if( $pushPayResult['code'] == Normal::SUC )
        {
            Order::instance()->edit(['id'=>$pushagain['order_id']], ['pay_success'=>1]);
            $againEditdata['pay_status']=1;
        }
        PushAgain::instance()->edit(['id'=>$pushagain['id']], $againEditdata);
        return $pushPayResult;
    }
}
